package com.sys.basics.filter.shiro;

import cn.hutool.json.JSONUtil;
import com.sys.basics.config.jsonRes.JsonResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.springframework.http.HttpStatus;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class QuitFilter extends LogoutFilter {


    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        Subject subject = SecurityUtils.getSubject();
        if(!subject.isAuthenticated()) {
            super.issueRedirect(request, response, super.getRedirectUrl());
            return true;
        }
        try {
            subject.logout();
            resp.setContentType("application/json; charset=utf-8");
            resp.setCharacterEncoding("UTF-8");
            resp.setStatus(HttpStatus.OK.value());
            PrintWriter out = resp.getWriter();
            JsonResult result = new JsonResult();
            result.setCode(String.valueOf(HttpStatus.OK.value()));
            result.setMessage("退出成功");
            out.println(JSONUtil.parseObj(result, false));
            out.flush();
            return false;
        } catch (SessionException ise) {
            super.issueRedirect(request, response, super.getRedirectUrl());
            return true;
        }
    }

}